﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Chart;
using Labthink.PCSoft.UniversalHost4.TcpCommands;
using Labthink.PCSoft.UniversalHost4.Utility;
using NLog.Fluent;

namespace Labthink.PCSoft.UniversalHost4.Instrument.MyControls
{
    public partial class UcCurves
    {
        private readonly Dictionary<int, int> _standards;
        private bool _isload;
        private DispatcherTimer _timer;
        private int index = 1;

        public UcCurves()
        {
            InitializeComponent();
            _standards = new Dictionary<int, int>();
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            if (index > 2) return;
            var data = Common.GetDataTemp(1);
            data.Single(d => d.DataNo == 7330201).Value = index;
            data.Single(d => d.DataNo == 7330206).Value = (double)index / 1000;
            data.Single(d => d.DataNo == 7330207).Value = (double)index / 100000;
            index++;
            var curve = TbCurves.FindName("Curve" + 1) as UcCurve;
            curve?.AddPoints(data);
        }

        public void InitCurves()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;

            for (int i = 1; i <= 12; i++)
            {
                if (i > Common.MaxCupCount)
                {
                    if (TbCurves.FindName("Cup" + i) is TabItem item)
                    {
                        TbCurves.Items.Remove(item);
                    }
                }
            }

            var data = Common.GetDataTemp(Common.CurrentStandard);
            var xd = data.Single(d => d.DataNo == 7330201);
            var yd0 = data.SingleOrDefault(d => d.DataNo == 7330205);
            var yd1 = data.SingleOrDefault(d => d.DataNo == 7330206);
            var yd2 = data.SingleOrDefault(d => d.DataNo == 7330207);
            var yd3 = data.SingleOrDefault(d => d.DataNo == 7330211);
            var max0 = 200.0;
            var max1 = 0.01;
            var max2 = 0.00000000000000001;
            var max3 = 0.00000000000000001;
            if (Common.CurrentStandard == 3)
            {
                max0 = 400;
                //max2 = 0.0001;
                yd1 = data.SingleOrDefault(d => d.DataNo == 7330209);
                yd2 = data.SingleOrDefault(d => d.DataNo == 7330210);
            }

            var name = LanguageManager.GetLanguageValue("DataCurve");
            for (int i = 1; i <= Common.MaxCupCount; i++)
            {
                var curve = TbCurves.FindName("Curve" + i) as UcCurve;
                if (curve != null)
                {
                    curve.Reset();
                    _standards.Add(i, Common.CurrentStandard);
                    curve.SetXAxis(xd, 10, 0);
                    curve.AddYAxis(yd0, true, true, max0);
                    if (yd1 != null)
                    {
                        curve.AddYAxis(yd1, true, true, max1);
                    }

                    if (yd2 != null)
                    {
                        curve.AddYAxis(yd2, true, true, max2);
                    }

                    if (yd3 != null)
                    {
                        curve.AddYAxis(yd3, true, true, max3);
                    }

                    curve.SetTitle($"{LanguageManager.GetLanguageValue("Cup" + i)} - {name}");
                    curve.Flash();
                }
            }
        }

        #region 事件处理

        private void _registerEvent()
        {
            Common.Instrument.Commands.OnReceiveParamDataHandler += DataConnection_OnReceiveParamDataHandler;
            Common.Instrument.Commands.OnReceiveTestStatusHandler += DataConnection_OnReceiveTestStatusHandler;
            Common.Instrument.Commands.OnReceiveRealtimeDataHandler += DataConnection_OnReceiveRealtimeDataHandler;
            Common.Instrument.Commands.OnReceiveTestStartHandler += DataConnection_OnReceiveTestStartHandler;
            Common.Instrument.Commands.OnReceiveResultsDataHandler += DataConnection_OnReceiveResultsDataHandler;
        }

        private void DataConnection_OnReceiveTestStatusHandler(object sender, StatusArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                if (e.Status.No == 10)
                {
                    var cups = e.Status.Tag.Split(',');
                    foreach (var c in cups)
                    {
                        if (!string.IsNullOrEmpty(c))
                        {
                            if (TbCurves.Items[c.ToInt() - 1] is TabItem ti) ti.IsEnabled = false;
                        }
                    }
                }
            });
        }

        private void DataConnection_OnReceiveResultsDataHandler(object sender, DataArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                Log.Debug().Message($"收到{e.Datas.DataSn}试验结果，显示曲线最后一点数值").Write();
                var curve = TbCurves.FindName("Curve" + e.Datas.DataSn) as UcCurve;
                curve?.ShowLastData();
            });
        }

        private void DataConnection_OnReceiveTestStartHandler(object sender, TestInfoArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                var curve = TbCurves.FindName("Curve" + e.Info.DataSn) as UcCurve;
                curve?.Clear();
            });

        }

        private void DataConnection_OnReceiveRealtimeDataHandler(object sender, DataArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                var curve = TbCurves.FindName("Curve" + e.Datas.DataSn) as UcCurve;
                curve?.AddPoints(e.Datas.Datas);
            });
        }

        private void DataConnection_OnReceiveParamDataHandler(object sender, DataArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                var cup = e.Datas.DataSn;
                if (TbCurves.Items[cup - 1] is TabItem ti) ti.IsEnabled = true;
                var s = e.Datas.Datas.Single(d => d.DataNo == 10078).Value.ToInt();
                if (_standards[cup] == s) return;
                _standards[cup] = s;
                var data = Common.GetDataTemp(s);
                var xd = data.Single(d => d.DataNo == 7330201);
                var yd0 = data.SingleOrDefault(d => d.DataNo == 7330205);
                var yd1 = data.SingleOrDefault(d => d.DataNo == 7330206);
                var yd2 = data.SingleOrDefault(d => d.DataNo == 7330207);
                var yd3 = data.SingleOrDefault(d => d.DataNo == 7330211);
                var max0 = 200.0;
                var max1 = 0.01;
                var max2 = 0.00000000000000001;
                var max3 = 0.00000000000000001;
                if (s == 3)
                {
                    max0 = 400;
                    //max2 = 0.0001;
                    yd1 = data.SingleOrDefault(d => d.DataNo == 7330209);
                    yd2 = data.SingleOrDefault(d => d.DataNo == 7330210);
                }

                var curve = TbCurves.FindName("Curve" + cup) as UcCurve;
                if (curve != null)
                {
                    curve.Reset();
                    curve.SetXAxis(xd, 10, 0);
                    curve.AddYAxis(yd0, true, true, max0);
                    if (yd1 != null)
                    {
                        curve.AddYAxis(yd1, true, true, max1);
                    }

                    if (yd2 != null)
                    {
                        curve.AddYAxis(yd2, true, true, max2);
                    }

                    if (yd3 != null)
                    {
                        curve.AddYAxis(yd3, true, true, max3);
                    }

                    var name = LanguageManager.GetLanguageValue("DataCurve");
                    curve.SetTitle($"{LanguageManager.GetLanguageValue("Cup" + cup)} - {name}");
                    curve.Flash();
                }
            });
        }

        #endregion

        private void UcCurves_OnLoaded(object sender, RoutedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;

            foreach (TabItem item in TbCurves.Items)
            {
                if (item.IsEnabled)
                {
                    item.IsSelected = true;
                    break;
                }
            }

            //Cup1.IsSelected = true;
            if (_isload) return;
            _isload = true;
            TbCurves.SelectedIndex = 0;
            //_initCurves();

            //_timer = new DispatcherTimer();
            //_timer.Interval = TimeSpan.FromSeconds(10);
            //_timer.Tick += _timer_Tick;
            _registerEvent();
        }
    }
}
